package com.baomidou.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.springboot.entity.*;
import com.baomidou.springboot.service.JsonDataService;
import com.baomidou.springboot.service.SessionAggrStatService;
import com.baomidou.springboot.service.TaskService;
import com.baomidou.springboot.spark.AnalysisMain;
import com.baomidou.springboot.utils.DateUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebMvcProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.stringtemplate.v4.ST;

import java.util.*;

import static com.baomidou.springboot.spark.AnalysisMain.Analysis1;

/**
 * Created by pcmmm on 17/6/8.
 */

@Controller
public class TaskController {
    @Autowired
    private  HttpServletRequest request;

    @Autowired
    private TaskService taskService;

    @Autowired
    private JsonDataService jsonDataService;

    /*@GetMapping("/getTask")
    public @ResponseBody Object getTask(){
        List<Task> tasks = taskService.selectList(null);
        String _result = JSONObject.toJSONString(tasks);
        JSONArray result =  JSONObject.parseArray(_result);
        return new Result<>(result);
    }

    @GetMapping("/addTask")
    public Object addTask(){

        Param param = new Param();
        List<String> city = Arrays.asList("北京","上海","广州");
        //List<String> sex = Arrays.asList("female");
        List<String> word = Arrays.asList("小米","华为");
        //param.setStartAge(20);
        //param.setEndAge(50);
        param.setCities(city);
        param.setSearchWords(word);
        //param.setSex("female");
        param.setProfessional(null);
        String paramString = JSON.toJSONString(param);
        String curDate = DateUtils.formatDate(new Date()).toString();
        Task task = new Task("task2", curDate,curDate,null,"testTask","0",paramString);
        JSONObject result = new JSONObject();
        result.put("result", taskService.insert(task));
        return result;
    }

    @RequestMapping(value = "/{id}")
    public Object getTask(@PathVariable("id") Integer id){
        Long task_id = Long.valueOf(id);
        Task task = taskService.selectById(id);
        return new Result<>(task);
    }

    @PostMapping("createTask")
    public void createTask(@ModelAttribute("Task") Task task){
        taskService.insert(task);
    }

    @GetMapping("/start/{id}")
    public @ResponseBody Object startTask(@PathVariable("id") Integer id){
        Long task_id = Long.valueOf(id);
        Task task = taskService.selectById(task_id);
        Analysis1(task);
        //SessionAggrStat sessionAggrStat = sessionAggrStatService.selectById(task.getTaskid());
        //JsonData jsonData = jsonDataService.selectById(1);
        //JSONObject result = JSONObject.parseObject(jsonData.getData());
        return new Result<>(task);
    }*/

    @GetMapping("/getData/{id}")
    public @ResponseBody Object getData(@PathVariable("id") Integer id){
        Long task_id = Long.valueOf(id);
        Map sessionMap = new HashMap();
        Map cityMap = new HashMap();
        Map timeMap = new HashMap();
        cityMap.put("task_id",task_id);
        cityMap.put("task_type","1");
        sessionMap.put("task_id", task_id);
        sessionMap.put("task_type","0");
        timeMap.put("task_id",task_id);
        timeMap.put("task_type","2");
        List<JsonData> sessionDatas = jsonDataService.selectByMap(sessionMap);
        List<JsonData> cityDatas = jsonDataService.selectByMap(cityMap);
        List<JsonData> timeDatas = jsonDataService.selectByMap(timeMap);
        Map<String, Object> resultmap = JSON.parseObject(
                sessionDatas.get(0).getData(),new TypeReference<Map<String, Object>>(){} );
        Map<String, Object> resultmap1 = JSON.parseObject(
                cityDatas.get(0).getData(),new TypeReference<Map<String, Object>>(){} );
        Map<String, Object> resultmap2 = JSON.parseObject(
                timeDatas.get(0).getData(),new TypeReference<Map<String, Object>>(){} );
        resultmap.putAll(resultmap1);
        resultmap.putAll(resultmap2);
        String jsonString = JSONObject.toJSONString(resultmap);
        //JsonData jsonData = jsonDataService.selectById(id);
        JSONObject result = JSONObject.parseObject(jsonString);
        return new Result<>(result);
    }


    @GetMapping("/index")
    public String index(Model model){
        List<Task>  tasks = taskService.selectList(null);
        model.addAttribute("tasks",tasks);
        return "index";
    }

    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object ajax() {
        String taskName = request.getParameter("taskName");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String startAge = request.getParameter("startAge");
        String endAge = request.getParameter("endAge");
        String sex = request.getParameter("sex");
        String city = request.getParameter("city");
        //Integer _startAge = Integer.valueOf(startAge);
        //Integer _endAge = Integer.valueOf(endAge);
        List<String> _city = new ArrayList<String>();
        List<String> _sex = new ArrayList<String>();
        List<String> _startDate = Arrays.asList(startDate);
        List<String> _endDate = Arrays.asList(endDate);
        List<String> _startAge = Arrays.asList(startAge);
        List<String> _endAge = Arrays.asList(endAge);
        if("0".equals(sex)){
            _sex = null;
        }else if("1".equals(sex)){
            _sex.add("male");
        }else {
            _sex.add("female");
        }
        String[] aa = city.split(",");
        for (int i = 0 ; i <aa.length ; i++ ) {
            if("1".equals(aa[i])){
                _city.add("北京");
            }else if("2".equals(aa[i])){
                _city.add("上海");
            }else if("3".equals(aa[i])){
                _city.add("广州");
            }else if("4".equals(aa[i])){
                _city.add("深圳");
            }else if("5".equals(aa[i])){
                _city.add("南京");
            }else if("6".equals(aa[i])){
                _city.add("杭州");
            }
        }
        Param param = new Param();
        if (_city.size()==0){
            param.setCities(null);
        }else {
            param.setCities(_city);
        }
        param.setStartDate(_startDate);
        param.setEndDate(_endDate);
        param.setStartAge(_startAge);
        param.setEndAge(_endAge);
        param.setSex(_sex);
        String paramString = JSON.toJSONString(param);
        String curDate = DateUtils.formatDate(new Date()).toString();
        String curTime = DateUtils.formatTime(new Date()).toString();
        Task task = new Task(taskName, curDate,curTime,null,"testTask","0",paramString);
        taskService.insertAndGetId(task);
        System.out.println("添加任务"+task.getTaskName()+",parms:"+task.getTaskParam());
        Analysis1(task);
        String endTime = DateUtils.formatTime(new Date()).toString();
        task.setFinishTime(endTime);
        taskService.insertOrUpdate(task);
        return new Result<>(task);
    }

}
